<script setup>
import dayjs from 'dayjs';
import { merge } from 'lodash-es';
import { basicLineYAxis } from '@/components/chart/options/baseOptions.js';
import { useWatch, useRequest } from '@/hooks';
import { usePickerOption } from '@/views/hooks.js';
import { useDownload } from '@/hooks/tool.js';
import { totalMeterOverview } from '@/api/index.js';
import CECharts from '@/components/chart/CECharts.vue';
import { TableList } from '@/components/MainComponents.js';
const props = defineProps({
  type: { type: String, default: '2' },
  inId: { type: String, default: '' },
  areaId: { type: String, default: null },
  radio: { type: String, default: '' },
  activeName: { type: String, default: 'overview' },
});
const typeList = {
  ELECTRICITY: '电',
  WATER: '水',
  AIR: '燃气',
  WARM: '用热',
};
const unitList = {
  ELECTRICITY: 'kwh',
  WATER: 'm³',
  AIR: 'm³',
  WARM: 'KJ',
};
const themeToggleStyle = {
  ELECTRICITY: {
    backgroundColor: '#113a35',
    color: '#76e612',
    quantity: '用电量',
    cost: '电费',
  },
  WATER: {
    backgroundColor: '#18334b',
    color: '#2bc9f2',
    quantity: '用水量',
    cost: '水费',
  },
  AIR: {
    backgroundColor: '#5b5023',
    color: '#bba755',
    quantity: '用气量',
    cost: '燃气费',
  },
  WARM: {
    backgroundColor: '#531e1e',
    color: '#ff9768',
    quantity: '用热量',
    cost: '供热费',
  },
};
const today = dayjs().format('YYYY-MM-DD');
const seriesArr = [
  {
    type: 'bar',
    barWidth: 25,
    yAxisIndex: 0,
  },
  {
    type: 'line',
    smooth: true,
    showSymbol: false,
    yAxisIndex: 1,
  },
];
const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: {
    type: 'year',
    fmt: 'yyyy',
    default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')],
  },
});
const dateRangeEC = ref(rangeType.value.d.default);
const yearRangeEC = ref({ sYear: null, eYear: null });
const ECParams = ref({
  dateType: 'd',
  startDate: dateRangeEC.value[0],
  endDate: dateRangeEC.value[1],
});
const tableData = ref(null);
const pageObj = ref({
  pageNum: 1,
  pageSize: 10,
});

const series1 = [
  {
    type: 'bar',
    barWidth: 25,
    yAxisIndex: 0,
  },
  {
    type: 'line',
    smooth: true,
    showSymbol: false,
    yAxisIndex: 1,
  },
  {
    type: 'line',
    smooth: true,
    showSymbol: false,
    yAxisIndex: 1,
  },
];
const series2 = [
  {
    type: 'bar',
    barWidth: 25,
    yAxisIndex: 0,
  },
  {
    type: 'line',
    smooth: true,
    showSymbol: false,
    yAxisIndex: 1,
  },
];
const columObj = ref({
  index: true,
  columnData: [
    {
      text: true,
      prop: 'recordDate',
      label: '日期',
    },
    {
      text: true,
      prop: 'paramValue',
      label: `总${themeToggleStyle?.[props.type]?.quantity}（${unitList[props.type]}）`,
    },
    {
      text: true,
      prop: 'chainValue',
      label: '环比（%）',
    },
  ],
});
const options = ref({
  color: ['#4992ff', '#5afe5d', '#eda422'],
  yAxis: [
    { name: `${themeToggleStyle?.[props.type]?.quantity}：${unitList[props.type]}` },
    merge({}, basicLineYAxis, {
      name: '同/环比：%',
      nameTextStyle: { align: 'right' },
    }),
  ],
  dataset: {
    dimensions: [
      'recordDate',
      { name: 'paramValue', displayName: themeToggleStyle?.[props.type]?.quantity },
      { name: 'chainValue', displayName: '环比' },
    ],
    source: [],
  },
  series: series2,
});
const [res, loading, run] = useRequest(totalMeterOverview, {
  manual: true,
  onSuccess: res => {
    pageObj.value = {
      pageNum: 1,
      pageSize: 10,
    };
    options.value.yAxis[0].name = `${themeToggleStyle[props.type]?.quantity}：${unitList[props.type]}`;
    if (ECParams.value.dateType === 'm') {
      options.value.dataset.dimensions = [
        'recordDate',
        { name: 'paramValue', displayName: themeToggleStyle[props.type]?.quantity },
        { name: 'togetherValue', displayName: '同比' },
        { name: 'chainValue', displayName: '环比' },
      ];
      options.value.series = series1;
      if (props.activeName === 'building') {
        columObj.value.columnData = [
          {
            text: true,
            prop: 'recordDate',
            label: '日期',
          },
          {
            text: true,
            prop: 'buildName',
            label: '区域名称',
          },
          {
            text: true,
            prop: 'paramValue',
            label: `总${themeToggleStyle[props.type].quantity}（${unitList[props.type]}）`,
          },
          {
            text: true,
            prop: 'togetherValue',
            label: '同比（%）',
          },
          {
            text: true,
            prop: 'chainValue',
            label: '环比（%）',
          },
        ];
      } else {
        columObj.value.columnData = [
          {
            text: true,
            prop: 'recordDate',
            label: '日期',
          },
          {
            text: true,
            prop: 'paramValue',
            label: `总${themeToggleStyle[props.type]?.quantity}（${unitList[props.type]}）`,
          },
          {
            text: true,
            prop: 'togetherValue',
            label: '同比（%）',
          },
          {
            text: true,
            prop: 'chainValue',
            label: '环比（%）',
          },
        ];
      }
    } else {
      options.value.dataset.dimensions = [
        'recordDate',
        { name: 'paramValue', displayName: themeToggleStyle[props.type]?.quantity },
        { name: 'chainValue', displayName: '环比' },
      ];
      options.value.series = series2;
      if (props.activeName === 'building') {
        columObj.value.columnData = [
          {
            text: true,
            prop: 'recordDate',
            label: '日期',
          },
          {
            text: true,
            prop: 'buildName',
            label: '区域名称',
          },
          {
            text: true,
            prop: 'paramValue',
            label: `总${themeToggleStyle[props.type].quantity}（${unitList[props.type]}）`,
          },
          {
            text: true,
            prop: 'chainValue',
            label: '环比（%）',
          },
        ];
      } else {
        columObj.value.columnData = [
          {
            text: true,
            prop: 'recordDate',
            label: '日期',
          },
          {
            text: true,
            prop: 'paramValue',
            label: `总${themeToggleStyle[props.type]?.quantity}（${unitList[props.type]}）`,
          },
          {
            text: true,
            prop: 'chainValue',
            label: '环比（%）',
          },
        ];
      }
    }
    options.value.dataset.source = res?.data?.tableData ?? [];
    tableData.value = res?.data?.tableData?.slice(0, 10) ?? [];
  },
});
const searchQuery = () => {
  let obj = {
    inId: props.inId,
    itemId: props.activeName === 'building' ? props.areaId : '',
    energyType: props.type,
    projectType: props.radio,
  };
  if (null != props.type) {
    setTimeout(
      -run({
        ...ECParams.value,
        ...obj,
      }),
      1000,
    );
  }
};
// 开始时间不能大于结束时间
const disabledDateStartEC = ref({
  disabledDate: time => {
    if (yearRangeEC.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRangeEC.value.eYear) || dayjs(time) < dayjs(yearRangeEC.value.eYear).subtract(2, 'year')
      );
    }
  },
});
const disabledDateEC = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRangeEC.value.sYear) || dayjs(time) > dayjs(yearRangeEC.value.sYear).add(2, 'year');
  },
});
const handleECDaterange = val => {
  ECParams.value.startDate = val?.[0] ?? null;
  ECParams.value.endDate = val?.[1] ?? null;
  searchQuery();
};
const handleECYearrange = () => {
  ECParams.value.startDate = yearRangeEC.value.sYear;
  ECParams.value.endDate = yearRangeEC.value.eYear;
  searchQuery();
};
const getList = e => {
  pageObj.value.pageNum = e.page;
  pageObj.value.pageSize = e.limit;
  tableData.value = res.value?.tableData?.slice((e.page - 1) * e.limit, e.page * e.limit);
};
const radioChange = val => {
  ECParams.value.dateType = val;
  if (val !== 'y') {
    dateRangeEC.value = rangeType.value[val].default;
    ECParams.value.startDate = dateRangeEC.value[0];
    ECParams.value.endDate = dateRangeEC.value[1];
  } else {
    yearRangeEC.value.sYear = rangeType.value.y.default[0];
    yearRangeEC.value.eYear = rangeType.value.y.default[1];
    ECParams.value.startDate = yearRangeEC.value.sYear;
    ECParams.value.endDate = yearRangeEC.value.eYear;
  }
  searchQuery();
};
const handleExport = () => {
  let obj = {
    inId: props.inId,
    itemId: props.activeName === 'building' ? props.areaId : '',
    energyType: props.type,
    projectType: props.radio,
  };
  useDownload('/energyservice/energy/totalMeterOverviewExport', { ...ECParams.value, ...obj }, `能耗趋势分析.xlsx`);
};
useWatch(
  () => props.type,
  n => {
    searchQuery();
  },
);
useWatch([() => props.inId, () => props.areaId], ([n1, n2], [o1, o2]) => {
  if (props.activeName === 'building') {
    if (n1 && n2) searchQuery();
  } else {
    if (n1 !== o1) {
      searchQuery();
    }
  }
});

useWatch(
  () => props.radio,
  n => {
    searchQuery();
  },
);
useWatch(
  () => props.activeName,
  n => {
    searchQuery();
  },
);
</script>
<template>
  <div class="u-h100 u-m20 u-ov">
    <div class="u-df-spb u-mb20 u-fs18">
      <span v-if="activeName === 'building'">建筑区域用{{ typeList[type] }}量概览</span>
      <span v-else>总{{ themeToggleStyle[type]?.quantity }}概览</span>
      <div class="u-fs16 u-reg-text u-ta-r">{{ today }}</div>
    </div>
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="grid-content u-base-fg">
          <div class="u-sec-text">年度累计总{{ themeToggleStyle[type]?.quantity }}（{{ unitList[type] }}）</div>
          <div class="u-mt20 u-prim-text">
            <span class="u-fs28 u-fw-b">
              {{ res?.yearData.replace('万', '') ?? '-' }}
              <span v-show="res?.yearData.includes('万')" class="u-fs14">万</span>
            </span>
            <div class="u-fs12 u-yellow u-mt10">统计开始时间：{{ res?.stasticStart?.slice(0, 10) ?? '-' }}</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content u-base-fg">
          <div class="u-sec-text">本月累计{{ themeToggleStyle[type]?.quantity }}（{{ unitList[type] }}）</div>
          <div class="u-mt20 u-prim-text">
            <span class="u-fs28 u-fw-b">
              {{ res?.monthData.replace('万', '') ?? '-' }}
              <span v-show="res?.monthData.includes('万')" class="u-fs14">万</span>
            </span>
            <div class="u-fs12 u-primary u-mt10">
              今日累计{{ themeToggleStyle[type]?.quantity }}（{{ unitList[type] }}）：{{ res?.dayData ?? '-' }}
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content u-base-fg">
          <div class="u-sec-text">上月累计{{ themeToggleStyle[type]?.quantity }}（{{ unitList[type] }}）</div>
          <div class="u-mt20 u-prim-text">
            <span class="u-fs28 u-fw-b">
              {{ res?.preMonthData.replace('万', '') ?? '-' }}
              <span v-show="res?.preMonthData.includes('万')" class="u-fs14">万</span>
            </span>
            <div class="u-fs12 u-mt10">
              <span v-if="res?.preMonthDataTogether > 0" class="u-red u-pr5">
                <i class="el-icon-caret-top"></i>
                {{ res?.preMonthDataTogether ?? '-' }}
              </span>
              <span v-else-if="res?.preMonthDataTogether < 0" class="u-green u-pr5">
                <i class="el-icon-caret-bottom"></i>
                <CaretBottom style="width: 1em; height: 1em" />
                {{ res?.preMonthDataTogether ?? '-' }}
              </span>
              <span v-else class="u-pr5">{{ res?.preMonthDataTogether ?? '-' }}</span>
              同比
              <span v-if="res?.preMonthDataChain > 0" class="u-red u-pr5 u-pl5">
                <i class="el-icon-caret-top"></i>
                {{ res?.preMonthDataChain ?? '-' }}
              </span>
              <span v-else-if="res?.preMonthDataChain < 0" class="u-green u-pr5 u-pl5">
                <i class="el-icon-caret-bottom"></i>
                {{ res?.preMonthDataChain ?? '-' }}
              </span>
              <span v-else class="u-pr5 u-pl5">{{ res?.preMonthDataChain ?? '-' }}</span>
              环比
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="grid-content u-base-fg">
          <div class="u-sec-text">昨日累计{{ themeToggleStyle[type]?.quantity }}（{{ unitList[type] }}）</div>
          <div class="u-mt20 u-prim-text">
            <span class="u-fs28 u-fw-b">
              {{ res?.predayData.replace('万', '') ?? '-' }}
              <span v-show="res?.predayData.includes('万')" class="u-fs14">万</span>
            </span>
            <div class="u-fs12 u-mt10">
              <span v-if="res?.predayDataChain > 0" class="u-red u-pr5">
                <i class="el-icon-caret-top"></i>
                {{ res?.predayDataChain ?? '-' }}
              </span>
              <span v-else-if="res?.predayDataChain < 0" class="u-green u-pr5">
                <i class="el-icon-caret-bottom"></i>
                {{ res?.predayDataChain ?? '-' }}
              </span>
              <span v-else class="u-pr5">{{ res?.predayDataChain ?? '-' }}</span>
              环比
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <div class="u-p20 u-mt20 u-mb20 u-base-fg u-br4">
      <el-form :model="ECParams" :inline="true" class="u-df-st qynh-form">
        <el-form-item prop="dateType" class="u-df-ct">
          <el-radio-group v-model="ECParams.dateType" size="mini" class="u-mr20" @input="radioChange">
            <el-radio-button label="d">日</el-radio-button>
            <el-radio-button label="m">月</el-radio-button>
            <el-radio-button label="y">年</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="rangeType[ECParams.dateType].type !== 'year'">
          <el-date-picker
            v-model="dateRangeEC"
            :type="rangeType[ECParams.dateType].type ?? 'daterange'"
            :key="rangeType[ECParams.dateType].type ?? 'daterange'"
            :value-format="rangeType[ECParams.dateType].fmt ?? 'yyyy-MM-dd'"
            :picker-options="rangeType[ECParams.dateType].pickerOptions"
            :clearable="false"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="mini"
            align="left"
            style="width: 240px"
            @change="handleECDaterange"
          />
        </el-form-item>
        <el-form-item v-else>
          <el-date-picker
            v-model="yearRangeEC.sYear"
            :picker-options="disabledDateStartEC"
            :clearable="false"
            type="year"
            value-format="yyyy"
            placeholder="开始年份"
            size="mini"
            style="width: 115px"
            class="u-mr5"
            @change="handleECYearrange"
          />
          <el-date-picker
            v-model="yearRangeEC.eYear"
            :picker-options="disabledDateEC"
            :clearable="false"
            type="year"
            value-format="yyyy"
            placeholder="结束年份"
            size="mini"
            style="width: 115px"
            @change="handleECYearrange"
          />
        </el-form-item>
      </el-form>
      <el-divider />
      <CECharts v-loading="loading" :options="options" type="line" class="chart-box" />
    </div>
    <div class="u-p20 u-base-fg u-br4">
      <div class="u-df-spb u-mb20">
        {{ activeName === 'building' ? '建筑区域' : '总' }}{{ themeToggleStyle[type]?.quantity }}列表
        <el-button size="small" type="primary" plain @click="handleExport">导出</el-button>
      </div>
      <TableList
        v-loading="loading"
        :total="res?.tableData?.length ?? 0"
        :height="530"
        :tableData="tableData"
        :pageObj="pageObj"
        :columObj="columObj"
        @getList="getList"
      ></TableList>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@import '../analysis/components/common.scss';

.u-pl5 {
  padding-left: 5px;
}

.u-pr5 {
  padding-right: 5px;
}

.el-row {
  margin-top: 20px;
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  height: 135px;
  padding: 20px;
  border-radius: 4px;
  font-size: 14px;
}
.el-icon-caret-top {
  width: 1em;
  height: 1em;
  color: #d31f08;
}
.el-icon-caret-bottom {
  width: 1em;
  height: 1em;
  color: #18e664;
}
.u-green {
  color: #18e664;
}
.u-red {
  color: #d31f08;
}
.u-fs28 {
  font-size: 28px;
}
.fee-statistics {
  display: flex;
  flex-direction: column;
}

.fee-quantity {
  height: 36px;
  margin-top: auto;
  border-radius: 0 0 4px 4px;

  > li {
    flex: 1;
    margin: 0 20px;
    font-size: 12px;
    color: rgba(255, 255, 255, 0.6);
  }
}

.dateForm :deep(.el-form-item) {
  margin-bottom: 0;
}

.chart-box {
  height: 300px;
}

.u-h-100 {
  height: 100px;
}

.u-ov {
  overflow-x: hidden;
  overflow-y: auto;
}
.qynh-form ::v-deep .el-form-item {
  margin-bottom: 0;
  margin-right: 0 !important;
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .el-form-item__content {
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 28px;
  }
}
::v-deep .el-radio-button--mini .el-radio-button__inner {
  padding: 6px 8px;
  height: 28px !important;
  margin-right: 3px;
  border-radius: 0;
}
.u-yellow {
  color: #e59215;
}
</style>
